package org.jetnuke.repository;

import org.apache.log4j.Logger;

import net.jforum.cache.CacheEngine;
import net.jforum.cache.Cacheable;

import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.MainConfigDAO;
import org.jetnuke.entities.MainConfig;

public class MainConfigRepository implements Cacheable {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(MainConfigRepository.class);

	private static CacheEngine cache;
	private static final String FQN = "jetnuke/mainConfig";

	public void setCacheEngine(CacheEngine cacheEngine) {
		cache = cacheEngine;

	}

	public static void loadMainConfig() {
		if (logger.isDebugEnabled()) {
			logger.debug("loadMainConfig() - start"); //$NON-NLS-1$
		}

		try {
			MainConfigDAO dao = DataAccessDriver.getInst().newMainConfigDAO();
			cache.add(FQN, dao.getMainConfig());
		} catch (Exception e) {
			logger.error("loadMainConfig()", e); //$NON-NLS-1$

			throw new RuntimeException("Error while loading the mainConfig: "
					+ e);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("loadMainConfig() - end"); //$NON-NLS-1$
		}
	}

	public static MainConfig getMainConfig() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getMainConfig() - start"); //$NON-NLS-1$
		}

		MainConfig cfg = (MainConfig) cache.get(FQN);

		if (logger.isDebugEnabled()) {
			logger.debug("getMainConfig() - end"); //$NON-NLS-1$
		}
		return cfg;
	}

	public synchronized static void clearCache() {
		if (logger.isDebugEnabled()) {
			logger.debug("clearCache() - start"); //$NON-NLS-1$
		}

		cache.remove(FQN);

		if (logger.isDebugEnabled()) {
			logger.debug("clearCache() - end"); //$NON-NLS-1$
		}
	}
}
